﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Jint.Native;
using MongoDB.Bson.IO;

namespace jsweb
{
   class JsonSerializer
   {
      public static string Serialize(JsObject jsObject)
      {
         var strWriter = new StringWriter();
         var bsonWriter = BsonWriter.Create(strWriter);
         bsonWriter.WriteStartDocument();
         Serialize(jsObject, bsonWriter);
         bsonWriter.WriteEndDocument();
         return strWriter.ToString();
      }

      public static void Serialize(JsObject jsObject, BsonWriter bsonWriter)
      {
         foreach (var key in jsObject.GetKeys())
         {
            JsInstance value = jsObject[key];
            if(!(jsObject is JsArray))
               bsonWriter.WriteName(key);

            if (value is JsString)
            {
               bsonWriter.WriteString(value.ToString());
            }
            else if (value is JsNumber)
            {
               bsonWriter.WriteDouble((double)value.Value);
            }
            else if(value is JsArray)
            {
               bsonWriter.WriteStartArray();
               // Recursive call
               Serialize(value as JsArray, bsonWriter);
               bsonWriter.WriteEndArray();
            }
            else if (value is JsObject)
            {
               bsonWriter.WriteStartDocument();
               // Recursive call
               Serialize(value as JsObject, bsonWriter);
               bsonWriter.WriteEndDocument();
            }
         }
      }
   }
}
